package com.ikkong.qy.util;

import java.util.Map;

import com.alibaba.druid.util.StringUtils;
import com.jfinal.kit.HttpKit;

/**
 * token管理
 * @author wukh
 * @2016年11月17日
 */
public class TokenManager {
	
	private String appId = "";
	private String appSecret = "";

	public TokenManager(String appId, String appSecret) {
		super();
		this.appId = appId;
		this.appSecret = appSecret;
	}

	private  String ACCESS_TOKEN = ""; // 网页授权token
	private  long EXPIRES_TIME = 0l; // 过期时间
	private  Thread getTokenThread = null;

	public String getEnableToken() {
		String result = "";
		if (StringUtils.isEmpty(ACCESS_TOKEN)) {
			try {
				result = getToken();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
		}

		long diff = EXPIRES_TIME - System.currentTimeMillis();
		if (diff > 60) {
			return ACCESS_TOKEN;
		} else if (diff > 10) {
			if (getTokenThread == null) {
				synchronized (this) {
					if (getTokenThread == null) {
						getTokenThread = new GetTokenThread();
						getTokenThread.start();
					}
				}
			}
			return ACCESS_TOKEN;
		} else {
			try {
				result = getToken();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
		}

	}

	private synchronized String getToken() throws Exception {
		String resp = "";
		String url ="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+appId+"&corpsecret=" + appSecret;
		System.out.println("访问地址："+url);
		resp = HttpKit.get(url, null);
		
		Map<String, Object> resultMap = CommonUtils.getJsonMap(resp);
		CommonUtils.tPrint(resultMap, "token");

		String token = (String) resultMap.get("access_token");
		long expires_time = Long.parseLong(resultMap.get("expires_in").toString());
		setToken(token, expires_time*1000);
		return token;
	}

	private void setToken(String token, long expires_time) {
		EXPIRES_TIME = System.currentTimeMillis() + expires_time;
		ACCESS_TOKEN = token;
	}

	class GetTokenThread extends Thread {
		
		@Override
		public void run() {
			try {
				getToken();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				getTokenThread = null;
			}
		}
	}

}
